<script>
/*
 * @Author: Your name
 * @Date:   2020-07-30 17:11:39
 * @Last Modified by:   Your name
 * @Last Modified time: 2020-08-06 16:29:28
 */
</script>
<template>
  <div>
    <el-breadcrumb separator-class="el-icon-arrow-right">
      <el-breadcrumb-item :to="{ path: '/home' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>用户管理</el-breadcrumb-item>
      <el-breadcrumb-item>用户列表</el-breadcrumb-item>
    </el-breadcrumb>
    <el-card class="box-card">
      <el-row :gutter="20">
        <el-col :span="10">
          <el-input placeholder="请输入内容">
            <el-button slot="append" icon="el-icon-search"></el-button>
          </el-input>
        </el-col>
        <el-col :span="6">
          <el-button type="primary" @click="addUser">添加用户</el-button>
        </el-col>
      </el-row>
      <el-table :data="userList" border stripe style="width: 100%">
        <el-table-column type="index"></el-table-column>
        <el-table-column
          label="姓名"
          width="180"
          prop="username"
        ></el-table-column>
        <el-table-column
          label="邮箱"
          width="180"
          prop="email"
        ></el-table-column>
        <el-table-column
          label="电话"
          width="180"
          prop="mobile"
        ></el-table-column>
        <el-table-column label="角色" prop="role_name"></el-table-column>
        <el-table-column label="状态"
          ><!-- 作用域插槽会覆盖prop所以prop可以不用写 -->
          <template slot-scope="scope">
            <el-switch
              v-model="scope.row.mg_state"
              @change="switchChange(scope.row)"
            ></el-switch>
          </template>
        </el-table-column>
        <!-- 操作列 -->
        <el-table-column label="操作" width="200px">
          <template slot-scope="scope">
            <el-tooltip
              class="item"
              effect="dark"
              content="删除"
              placement="top"
            >
              <el-button
                type="danger"
                size="mini"
                icon="el-icon-delete"
                @click="userDelete(scope.row)"
              ></el-button>
            </el-tooltip>
            <el-tooltip
              class="item"
              effect="dark"
              content="编辑"
              placement="top"
            >
              <el-button
                type="primary"
                size="mini"
                icon="el-icon-edit"
                @click="userEdit(scope.row)"
              ></el-button>
            </el-tooltip>
            <el-tooltip
              class="item"
              effect="dark"
              content="分配"
              placement="top"
            >
              <el-button
                type="warning"
                size="mini"
                icon="el-icon-s-help"
                @click="userHelp(scope.row)"
              ></el-button>
            </el-tooltip>
          </template>
        </el-table-column>
      </el-table>
      <!-- 用户列表分页 -->
      <el-pagination
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        :page-sizes="[1, 2, 5, 10]"
        :current-page="listParams.pagenum"
        :page-size="listParams.pagesize"
        layout="total, sizes, prev, pager, next, jumper"
        :total="totlePages"
      >
      </el-pagination>
      <!-- 弹出编辑对话框 -->
      <el-dialog
        title="编辑用户"
        @close="editClose"
        width="50%"
        :visible.sync="editDialogFormVisible"
      >
        <el-form
          label-width="80px"
          ref="editFormRef"
          :model="editFormData"
          :rules="editFormRules"
        >
          <el-form-item label="用户名">
            <el-input
              :disabled="true"
              v-model="editFormData.username"
            ></el-input>
          </el-form-item>
          <el-form-item label="邮箱" prop="email">
            <el-input v-model="editFormData.email"></el-input>
          </el-form-item>
          <el-form-item label="电话" prop="mobile">
            <el-input v-model="editFormData.mobile"></el-input>
          </el-form-item>
        </el-form>
        <div slot="footer" class="dialog-footer">
          <el-button @click="editDialogFormVisible = false">取 消</el-button>
          <el-button type="primary" @click="doUserEdit">确 定</el-button>
        </div>
      </el-dialog>
      <!-- 添加用户对话框 -->
      <el-dialog
        title="编辑用户"
        @close="addClose"
        width="50%"
        :visible.sync="addDialogFormVisible"
      >
        <el-form
          label-width="80px"
          ref="addFormRef"
          :model="addFormData"
          :rules="addFormRules"
        >
          <el-form-item label="用户名" prop="username">
            <el-input v-model="addFormData.username"></el-input>
          </el-form-item>
          <el-form-item label="密码" prop="password">
            <el-input v-model="addFormData.password"></el-input>
          </el-form-item>
          <el-form-item label="邮箱" prop="email">
            <el-input v-model="addFormData.email"></el-input>
          </el-form-item>
          <el-form-item label="电话" prop="mobile">
            <el-input v-model="addFormData.mobile"></el-input>
          </el-form-item>
        </el-form>
        <div slot="footer" class="dialog-footer">
          <el-button @click="addDialogFormVisible = false">取 消</el-button>
          <el-button type="primary" @click="doUseAdd">确 定</el-button>
        </div>
      </el-dialog>
      <!-- 分配权限的弹出框 -->
      <el-dialog
        title="编辑用户"
        width="50%"
        :visible.sync="helpDialogVisible"
      >
        <p>当前用户：    {{userinfo.username}}</p>
        <p>当前用户角色：{{userinfo.role_name}}</p>
        <p>
          分配新角色：
          <el-select v-model="selectedRoleId" clearable placeholder="请选择">
            <el-option
              v-for="item in rolesList"
              :key="item.id"
              :label="item.roleName"
              :value="item.id"
            >
            </el-option>
          </el-select>
        </p>
        <div slot="footer" class="dialog-footer">
          <el-button @click="helpDialogVisible = false">取 消</el-button>
          <el-button type="primary" @click="doUserHelp">确 定</el-button>
        </div>
      </el-dialog>
    </el-card>
  </div>
</template>
<script>
import { request, request2 } from 'network/request.js'
import { checkEmail, checkMobile } from 'common/tools/util.js'
export default {
  name: 'User',
  data() {
    return {
      // 储存用户列表数据
      userList: [],
      // 请求用户数据相关参数
      listParams: {
        query: '',
        pagenum: 1,
        pagesize: 2
      },
      // 总页数
      totlePages: 0,
      // 控制添加对话框是否显示
      addDialogFormVisible: false,
      // 添加用户信息
      addFormData: {
        username: '',
        password: '',
        email: '',
        mobile: ''
      },
      // 添加表单中的验证
      addFormRules: {
        username: [
          { required: true, message: '请输入用户名', trigger: 'blur' },
          { min: 3, max: 20, message: '长度在 3 到 20 个字符', trigger: 'blur' }
        ],
        password: [
          { required: true, message: '请输入密码', trigger: 'blur' },
          {
            min: 6,
            max: 18,
            message: '密码长度在 6 到 18 个字符',
            trigger: 'blur'
          }
        ],
        email: [
          { required: true, message: '请输入用户邮箱', trigger: 'blur' },
          { validator: checkEmail, trigger: 'blur' }
        ],
        mobile: [
          { required: true, message: '请输入用户手机', trigger: 'blur' },
          { validator: checkMobile, trigger: 'blur' }
        ]
      },
      // 控制编辑对话框是否显示
      editDialogFormVisible: false,
      // 编辑表单中的用户信息对象
      editFormData: {},
      // 编辑用户表单中的验证
      editFormRules: {
        email: [
          { required: true, message: '请输入用户邮箱', trigger: 'blur' },
          { validator: checkEmail, trigger: 'blur' }
        ],
        mobile: [
          { required: true, message: '请输入用户手机', trigger: 'blur' },
          { validator: checkMobile, trigger: 'blur' }
        ]
      },
      // 控制是否显示分配用户角色弹出框
      helpDialogVisible: false,
      // 分配角色弹框中存放user数据
      userinfo: {},
      // 角色列表
      rolesList: [],
      // 被选中的角色id值
      selectedRoleId: ''
    }
  },
  methods: {
    // 请求用户列表的数目
    async getUserList() {
      let res = await request2({
        method: 'get',
        url: '/users',
        params: this.listParams
      })
      this.userList = res.data.users
      this.totlePages = res.data.total
    },
    // 操作分页
    // 监听每页条数
    handleSizeChange(value) {
      this.listParams.pagesize = value
      this.getUserList()
    },
    // 监听当前页数
    handleCurrentChange(value) {
      this.listParams.pagenum = value
      this.getUserList()
    },
    // 监听开关的点击事件
    async switchChange(userinfo) {
      // console.log(userinfo)
      let res = await request2({
        method: 'put',
        url: `/users/${userinfo.id}/state/${userinfo.mg_state}`
      })
      if (res.meta.status !== 200) {
        this.$message.error('修改用户状态失败')
        return
      }
      this.$message.success('修改用户状态成功')
    },
    // 点击添加按钮显示用户添加信息对话框
    addUser(userinfo) {
      this.addDialogFormVisible = true
    },
    // 确认添加点击事件
    doUseAdd() {
      this.addDialogFormVisible = false
      this.$refs.addFormRef.validate(async valid => {
        if (!valid) return
        let res = await request2({
          method: 'post',
          url: `/users`,
          data: {
            username: this.addFormData.username,
            password: this.addFormData.password,
            email: this.addFormData.email,
            mobile: this.addFormData.mobile
          }
        })
        console.log(res)
        if (res.meta.status !== 201) {
          this.$message.error('添加用户失败')
          return
        }
        this.$message.success('添加用户成功')
        this.getUserList()
      })
    },
    // 删除操作
    userDelete(userinfo) {
      this.$confirm('此操作将永久删除该用户, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      })
        .then(async () => {
          let res = await request2({
            method: 'delete',
            url: `/users/${userinfo.id}`
          })
          if (res.meta.status !== 200) {
            this.$message.error('删除失败')
            return
          }
          this.$message({
            type: 'success',
            message: '删除成功!'
          })
          this.getUserList()
        })
        .catch(() => {
          this.$message({
            type: 'info',
            message: '已取消删除'
          })
        })
    },
    // 编辑按钮点击事件
    userEdit(userinfo) {
      this.editDialogFormVisible = true
      this.editFormData = userinfo
    },
    // 确认提交编辑点击事件
    doUserEdit() {
      this.editDialogFormVisible = false
      this.$refs.editFormRef.validate(async valid => {
        if (!valid) return
        let res = await request2({
          method: 'put',
          url: `/users/${this.editFormData.id}`,
          data: {
            email: this.editFormData.email,
            mobile: this.editFormData.mobile
          }
        })
        console.log('edit:' + res)
        if (res.meta.status !== 200) {
          this.$message.error('编辑用户失败')
          return
        }
        this.$message.success('编辑用户成功')
        this.getUserList()
      })
    },
    // 点击分配用户权限按钮
    async userHelp(userinfo) {
      this.helpDialogVisible = true
      this.userinfo = userinfo
      // 获取角色列表
      let res = await request2({
        url: 'roles',
        method: 'get'
      })
      if(res.meta.status !== 200) {
        this.$message.error('获取角色列表失败')
        return
      }
      this.rolesList = res.data
    },
    // 确认提交用户分配权限
    async doUserHelp() {
      if(!this.selectedRoleId) {
        this.$message.error('请输入要分配的角色')
        return
      }
      let res = await request2({
        url: `/users/${this.userinfo.id}/role`,
        method: 'put',
        data: {
          rid: this.selectedRoleId
        }
      })
      console.log(res)
      console.log(this.selectedRoleId)
      this.helpDialogVisible = false
    },
    // 关闭用户编辑框重置表单
    editClose() {
      this.$refs.editFormRef.resetFields()
    },
    // 关闭用户添加框重置表单
    addClose() {
      this.$refs.addFormRef.resetFields()
    }
  },
  created() {
    this.getUserList()
  }
}
</script>
<style lang="less" scoped>
.box-card {
  margin-top: 20px;
  box-shadow: 0 1px 1px rgba(0, 0, 0, 0.15);
  .el-table {
    margin-top: 15px;
    text-align: center;
  }
  .el-pagination {
    margin-top: 20px;
  }
}
</style>
